package qz.lixinyu.modules.company.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import qz.lixinyu.common.utils.PageUtils;
import qz.lixinyu.common.utils.Query;

import qz.lixinyu.common.utils.R;
import qz.lixinyu.modules.company.dao.QyCompanyDao;
import qz.lixinyu.modules.company.entity.QyCompanyEntity;
import qz.lixinyu.modules.company.service.QyCompanyService;
import qz.lixinyu.modules.sys.entity.QzEntity;
import qz.lixinyu.modules.sys.entity.SysUserEntity;
import qz.lixinyu.modules.sys.service.QzService;
import qz.lixinyu.modules.sys.service.SysUserService;


@Service("qyCompanyService")
public class QyCompanyServiceImpl extends ServiceImpl<QyCompanyDao, QyCompanyEntity> implements QyCompanyService {
    @Autowired
    private QyCompanyService qyCompanyService;
    @Autowired
    private QzService qzService;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<QyCompanyEntity> page = this.page(
                new Query<QyCompanyEntity>().getPage(params),
                new QueryWrapper<QyCompanyEntity>()
                        .like(StringUtils.isNotBlank((String) params.get("key")),"name",params.get("key"))
                        .or()
                        .like(StringUtils.isNotBlank((String) params.get("key")),"title",params.get("key"))
        );

        return new PageUtils(page);
    }

    /***
     * 1.投递简历更新qyCompany的投递人数/和总数
     * 2.新增中间表user_qz投递人账号和职位的id
     * @param id(登录人的id) qyCompanyId(职位的id)
     * @return
     */
    @Override
    public R saveCompanyAndQZ(Long id, Long qyCompanyId) {
        // 检查用户是否已经投递过该职位
        QueryWrapper queryWrapperUser = new QueryWrapper<>();
        queryWrapperUser.eq("user_id",id);
        SysUserEntity one1 = sysUserService.getOne(queryWrapperUser);
        QueryWrapper<QzEntity> qzQueryWrapper = new QueryWrapper<>();
        qzQueryWrapper.eq("username", one1.getUsername()).eq("company_id", qyCompanyId);
        QzEntity existingQz = qzService.getOne(qzQueryWrapper);
        if (existingQz != null) {
            // 若已经投递过，可以抛出自定义异常或打印日志等方式提示
            return R.error("你已经投递过了");
        }
        QyCompanyEntity qyCompany = new QyCompanyEntity();
        qyCompany.setId(qyCompanyId);
        //通过职位id拿到职位的投递人数/和总数   +1
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",qyCompanyId);
        QyCompanyEntity qyCompanyEntity = qyCompanyService.getOne(queryWrapper);
        Integer total = qyCompanyEntity.getTotal();   // 总数
        Integer num = qyCompanyEntity.getNum();   // 录取人数
        //通过率
//        double passRate =0.0;
//        if(total==0){  //没有人投递为100%
//            passRate=100.0;
//        }else {
//            passRate=(num/total)*100;
//        }
        //投递后更新投递人数/和总数
        Integer newTotal = total+1;
        //Integer newNum = num+1;
        //qyCompanyEntity.setNum(newNum);
        qyCompanyEntity.setTotal(newTotal);
        //System.out.println(qyCompanyEntity);
        qyCompanyService.updateById(qyCompanyEntity);
        //2.新增中间表user_qz投递人账号和职位的id
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id",id);
        SysUserEntity one = sysUserService.getOne(queryWrapper1);
        QzEntity qz = new QzEntity();
        qz.setUsername(one.getUsername());
        qz.setCompanyId(qyCompanyId);
        qz.setStatus(0);//投递中
        qzService.save(qz);
//        R r = new R();
//        r.put("passRate",passRate);
        return R.ok("投递成功");
    }

    @Override
    public Double getPassRate(Long qyCompanyId) {
        //通过职位id拿到职位的投递人数/和总数   +1
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",qyCompanyId);
        QyCompanyEntity qyCompanyEntity = qyCompanyService.getOne(queryWrapper);
        Integer total = qyCompanyEntity.getTotal();   // 总数
        Integer num = qyCompanyEntity.getNum();   // 录取人数
        //通过率
        double passRate =0.0;
        if(total==0){  //没有人投递为100%
            passRate=100.0;
        }else {
            passRate=((double)num/total)*100;
//            System.out.println("通过率为"+passRate);
        }
        // 使用 DecimalFormat 格式化，但返回前仍需转换为 Double
        DecimalFormat df = new DecimalFormat("0.00");
        passRate = Double.parseDouble(df.format(passRate));
        return passRate;
    }

    @Override
    public PageUtils queryPageByCategorty(Map<String, Object> params) {
        // 获取参数中的 key 并转换为字符串
        Object keyObj = params.get("key");
        String category = keyObj != null ? keyObj.toString() : null;

        QueryWrapper<QyCompanyEntity> queryWrapper = new QueryWrapper<>();
        // 判断 category 是否为 "全部"
        if (!"全部".equals(category) && StringUtils.isNotBlank(category)) {
            // 如果不是 "全部" 且 category 不为空，则添加根据 category 过滤的条件
            queryWrapper.eq("categorty", category);
        }

        // 执行分页查询
        IPage<QyCompanyEntity> page = this.page(
                new Query<QyCompanyEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);

    }
    //最新过滤
    @Override
    public PageUtils getChangSortList(Map<String, Object> params) {
        // 获取参数中的 key 并转换为字符串
        Object keyObj = params.get("key");
        String sort = keyObj != null ? keyObj.toString() : null;

        QueryWrapper<QyCompanyEntity> queryWrapper = new QueryWrapper<>();

        // 根据 sort 的值设置不同的排序逻辑
        if ("latest".equals(sort)) {
            // 如果是最新，按照创建时间降序排序
            queryWrapper.orderByDesc("create_time");
        } else if ("recommended".equals(sort)) {
            // 1.找到简历你的意向职位sys_user的position
            //2.筛选出qycompany的categorty和position相同的
            Long userId = Long.valueOf(params.get("userId").toString());
            QueryWrapper queryWrapperUser = new QueryWrapper<>();
            queryWrapperUser.eq(StringUtils.isNotBlank((String) params.get("userId")),"user_id",params.get("userId"));
            SysUserEntity userServiceOne = sysUserService.getOne(queryWrapperUser);
            String position = userServiceOne.getPosition();
            queryWrapper.eq(StringUtils.isNotBlank(position),"categorty",position);

        }

        // 执行分页查询
        IPage<QyCompanyEntity> page = this.page(
                new Query<QyCompanyEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

}